<template>
  <div class="three">
    <el-upload
      class="upload-demo"
      drag
      multiple
      action=""
      :auto-upload="false"
      :file-list="fileList"
      :show-file-list="false"
      :on-change="handleFileChange"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div>
        <span>文件数量：{{ fileList.length }}</span>
        <span>；</span>
        <span>总大小：{{ (total / 1024).toFixed(2) }} MB</span><br>
      </div>
    </el-upload>
    <el-button
      style="margin-left: 10px"
      size="small"
      type="success"
      @click="submitUpload"
    >开始上传</el-button>
    <el-button
      style="margin-left: 10px"
      size="small"
      type="danger"
      @click="removeAllFile"
    >清除所有</el-button>
    <el-button
      style="margin-left: 10px"
      size="small"
      type="warning"
      @click="cancelAllUploads"
    >停止上传</el-button>
    <el-table :data="fileList" border style="margin-top: 20px">
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="size" label="大小 (KB)" width="100">
        <template #default="scope">
          {{ (scope.row.size / 1024).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="scope">
          <span v-if="progress[scope.row.uid] === 100">上传成功</span>
          <span v-else-if="progress[scope.row.uid] === 0">待上传</span>
          <span v-else>上传中</span>

        </template>
      </el-table-column>
      <el-table-column label="进度" width="150">
        <template #default="scope">
          <el-progress :text-inside="true" :stroke-width="24" :percentage="progress[scope.row.uid]" status="success" />
          <!-- <el-progress
            :percentage="scope.row.progress"
            v-if="scope.row.progress <= 100 && scope.row.progress >= 0"
          /> -->
          <!-- v-if="scope.row.uploading" -->
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
            size="small"
            type="info"
            @click="cancelSingleUpload(scope.row)"
          >
            取消
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="removeFile(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      items: [
        { type: '', label: '正在上传' },
        { type: 'success', label: '上传成功' },
        { type: 'info', label: '待上传' }
      ],
      progress: {},
      uploading: false,
      fileList: [],
      cancelTokens: {}
    }
  },
  computed: {
    total() {
      if (this.fileList.length === 0) return 0
      return this.fileList.reduce((res, item) => res + item.size, 0) / 1024
    }
  },
  methods: {
    removeFile(file) {
      this.fileList = this.fileList.filter(fileItem => fileItem.uid !== file.uid)
    },
    removeAllFile() {
      this.fileList = []
      this.progress = {}
    },
    handleFileChange(file, fileList) {
      console.log(file, fileList)

      this.cancelTokens = {}
      this.progress = {}
      this.fileList = []
      fileList.forEach((file) => {
        file.uploading = false
        file.progress = 0
        this.$set(this.progress, file.uid, 0)
      })
      this.fileList = fileList
      console.log(this.fileList)
    },
    uploadFile(file, uid) {
      const formData = new FormData()
      formData.append('file', file)

      const source = axios.CancelToken.source()
      this.$set(this.cancelTokens, uid, source)
      console.log('取消令牌', this.cancelTokens)

      // this.cancelTokens[uid] = source;

      // formData.append("type", "contract");
      return axios.post(
        'https://jsonplaceholder.typicode.com/posts/',
        formData,
        {
          cancelToken: source.token,
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            )
            file.progress = percentCompleted
            this.$set(this.progress, uid, percentCompleted)
            console.log(this.progress)
            console.log(`Upload progress: ${file.progress}%`)
          }
        }
      )
      // .then((response) => {
      //   file.uploading = false;
      //   // 处理上传成功的响应
      // })
    },
    submitUpload() {
      const uploadList = this.fileList.map((item) => {
        return this.uploadFile(item.raw, item.uid)
      })
      Promise.allSettled(uploadList)
        .then((res) => {
          console.log('res:', res)
        })
        .catch((error) => {
          console.error('上传失败:', error)
        })

      // this.fileList.forEach((file) => {
      //   const formData = new FormData();
      //   formData.append('file', file.raw);

      // const source = axios.CancelToken.source();
      // this.cancelTokens[file.uid] = source;

      //   file.uploading = true;
      //   file.progress = 0;

      //   axios.post('https://jsonplaceholder.typicode.com/posts/', formData, {
      //     cancelToken: source.token,
      //     onUploadProgress: (progressEvent) => {
      //       const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      //       file.progress = percentCompleted;
      //     }
      //   })
      //   .then((response) => {
      //     file.uploading = false;
      //     // 处理上传成功的响应
      //     console.log('上传成功:', response);
      //   })
      //   .catch((error) => {
      //     if (axios.isCancel(error)) {
      //       file.uploading = false;
      //       console.log('上传取消:', file.name);
      //     } else {
      //       file.uploading = false;
      //       // 处理上传失败的错误
      //       console.error('上传失败:', error);
      //     }
      //   });
      // });
    },
    cancelAllUploads() {
      Object.values(this.cancelTokens).forEach((source) => {
        source.cancel('全部上传已取消')
      })
      Message.success('全部上传已取消')
      this.cancelTokens = {}
    },
    cancelSingleUpload(file) {
      const source = this.cancelTokens[file.uid]
      if (source) {
        source.cancel('单个文件上传已取消')
        delete this.cancelTokens[file.uid]
        Message.success('单个文件上传已取消')
      }
    }
  }
}
</script>

<style scoped lang="scss">
/* 样式部分 */
::v-deep .el-upload.el-upload--text{
  width: 100%;
  .el-upload-dragger{
    width: 100%;
  }
}
</style>
